import { Pagination } from "antd";
import { FC, useEffect, useState } from "react";
import {
  LIST_PAGESIZE,
  LIST_PAGE_PARAM_KEY,
  LIST_PAGESIZE_PARAM_KEY,
} from "../../constant";
import { useLocation, useNavigate, useSearchParams } from "react-router-dom";

type PropsType = {
  total: number;
};

const ListPage: FC<PropsType> = (props) => {
  const { total } = props;
  const [current, setCurrent] = useState(1);
  const [pageSize, setPageSize] = useState(LIST_PAGESIZE);
  const [searchParams] = useSearchParams();
  const { pathname } = useLocation();
  const nav = useNavigate();

  // 将 url 上的参数同步到组件中
  useEffect(() => {
    const page = parseInt(searchParams.get(LIST_PAGE_PARAM_KEY) || "1");
    const pageSize = parseInt(
      searchParams.get(LIST_PAGESIZE_PARAM_KEY) || `${LIST_PAGESIZE}`
    );
    setCurrent(page);
    setPageSize(pageSize);
  }, [searchParams]);

  const handlePageChange = (page: number, pageSize: number) => {
    searchParams.set("page", `${page}`);
    searchParams.set("pageSize", `${pageSize}`);
    nav({
      pathname,
      search: searchParams.toString(),
    });
  };

  return (
    <Pagination
      current={current}
      pageSize={pageSize}
      total={total}
      onChange={handlePageChange}
    />
  );
};

export default ListPage;
